import express from 'express';
import { body, query, param, validationResult } from 'express-validator';
import { Task, Admin } from '../models/index.js';
import { authenticateAdmin } from '../middleware/auth.js';
import { catchAsync, BusinessError, NotFoundError } from '../middleware/errorHandler.js';
import { success, paginated } from '../utils/response.js';
import { Op } from 'sequelize';

const router = express.Router();

// 获取任务列表
router.get('/list',
  authenticateAdmin,
  [
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间'),
    query('keyword').optional().isLength({ max: 100 }).withMessage('关键词不能超过100个字符'),
    query('is_completed').optional().custom((value) => {
      if (value === null || value === undefined || value === '' || value === 'null') return true;
      if (value === 'true' || value === 'false' || value === true || value === false) return true;
      throw new Error('完成状态参数必须是布尔值');
    }),
    query('is_important').optional().custom((value) => {
      if (value === null || value === undefined || value === '' || value === 'null') return true;
      if (value === 'true' || value === 'false' || value === true || value === false) return true;
      throw new Error('重要状态参数必须是布尔值');
    }),
    query('priority').optional().custom((value) => {
      if (value === null || value === undefined || value === '' || value === 'null') return true;
      if (['low', 'medium', 'high'].includes(value)) return true;
      throw new Error('优先级参数无效');
    })
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { 
      page = 1, 
      limit = 20, 
      keyword, 
      is_completed, 
      is_important,
      priority 
    } = req.query;

    const offset = (page - 1) * limit;
    
    // 构建查询条件
    const where = {};
    
    if (keyword) {
      where[Op.or] = [
        { title: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } }
      ];
    }
    
    if (is_completed !== undefined && is_completed !== '' && is_completed !== 'null') {
      where.is_completed = is_completed === 'true' || is_completed === true;
    }

    if (is_important !== undefined && is_important !== '' && is_important !== 'null') {
      where.is_important = is_important === 'true' || is_important === true;
    }

    if (priority && priority !== 'null') {
      where.priority = priority;
    }

    const { count, rows } = await Task.findAndCountAll({
      where,
      include: [
        { 
          association: 'creator', 
          attributes: ['id', 'username', 'nickname'] 
        },
        { 
          association: 'updater', 
          attributes: ['id', 'username', 'nickname'],
          required: false
        }
      ],
      order: [
        ['is_important', 'DESC'],
        ['is_completed', 'ASC'],
        ['created_at', 'DESC']
      ],
      limit: parseInt(limit),
      offset
    });

    res.json(paginated(rows, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: count,
      pages: Math.ceil(count / limit)
    }, '获取任务列表成功'));
  })
);

// 获取重要任务（用于通知）
router.get('/important',
  authenticateAdmin,
  catchAsync(async (req, res) => {
    const tasks = await Task.findImportantTasks({
      include: [
        { 
          association: 'creator', 
          attributes: ['id', 'username', 'nickname'] 
        }
      ],
      limit: 10
    });

    res.json(success(tasks, '获取重要任务成功'));
  })
);

// 获取任务详情
router.get('/:id',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('任务ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { id } = req.params;
    
    const task = await Task.findByPk(id, {
      include: [
        { 
          association: 'creator', 
          attributes: ['id', 'username', 'nickname'] 
        },
        { 
          association: 'updater', 
          attributes: ['id', 'username', 'nickname'],
          required: false
        }
      ]
    });
    
    if (!task) {
      throw new NotFoundError('任务不存在');
    }
    
    res.json(success(task, '获取任务详情成功'));
  })
);

// 创建任务
router.post('/',
  authenticateAdmin,
  [
    body('title').notEmpty().isLength({ max: 200 }).withMessage('任务标题不能为空且不能超过200个字符'),
    body('description').optional().isLength({ max: 10000 }).withMessage('任务描述不能超过10000个字符'),
    body('is_important').optional().isBoolean().withMessage('重要状态必须是布尔值'),
    body('priority').optional().isIn(['low', 'medium', 'high']).withMessage('优先级参数无效')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { title, description, is_important, priority } = req.body;
    const adminId = req.admin.id;

    const task = await Task.createTask({
      title,
      description,
      is_important: is_important || false,
      priority: priority || 'medium',
      created_by: adminId
    });
    
    // 重新查询完整的任务信息
    const completeTask = await Task.findByPk(task.id, {
      include: [
        { 
          association: 'creator', 
          attributes: ['id', 'username', 'nickname'] 
        }
      ]
    });
    
    res.json(success(completeTask, '任务创建成功'));
  })
);

// 更新任务
router.put('/:id',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('任务ID必须是正整数'),
    body('title').optional().isLength({ min: 1, max: 200 }).withMessage('任务标题不能为空且不能超过200个字符'),
    body('description').optional().isLength({ max: 10000 }).withMessage('任务描述不能超过10000个字符'),
    body('is_completed').optional().isBoolean().withMessage('完成状态必须是布尔值'),
    body('is_important').optional().isBoolean().withMessage('重要状态必须是布尔值'),
    body('priority').optional().isIn(['low', 'medium', 'high']).withMessage('优先级参数无效')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { id } = req.params;
    const { title, description, is_completed, is_important, priority } = req.body;
    const adminId = req.admin.id;

    const updateData = {};
    if (title !== undefined) updateData.title = title;
    if (description !== undefined) updateData.description = description;
    if (is_completed !== undefined) updateData.is_completed = is_completed;
    if (is_important !== undefined) updateData.is_important = is_important;
    if (priority !== undefined) updateData.priority = priority;
    
    const task = await Task.updateTask(id, updateData, adminId);
    
    // 重新查询完整的任务信息
    const completeTask = await Task.findByPk(task.id, {
      include: [
        { 
          association: 'creator', 
          attributes: ['id', 'username', 'nickname'] 
        },
        { 
          association: 'updater', 
          attributes: ['id', 'username', 'nickname'],
          required: false
        }
      ]
    });
    
    res.json(success(completeTask, '任务更新成功'));
  })
);

// 删除任务
router.delete('/:id',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('任务ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { id } = req.params;
    
    const task = await Task.findByPk(id);
    if (!task) {
      throw new NotFoundError('任务不存在');
    }
    
    await task.destroy();
    
    res.json(success(null, '任务删除成功'));
  })
);

// 批量操作任务
router.post('/batch',
  authenticateAdmin,
  [
    body('action').isIn(['complete', 'incomplete', 'delete', 'important', 'unimportant']).withMessage('操作类型无效'),
    body('task_ids').isArray({ min: 1 }).withMessage('任务ID列表不能为空'),
    body('task_ids.*').isInt({ min: 1 }).withMessage('任务ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { action, task_ids } = req.body;
    const adminId = req.admin.id;
    
    const updateData = { updated_by: adminId };
    
    switch (action) {
      case 'complete':
        updateData.is_completed = true;
        updateData.completed_at = new Date();
        break;
      case 'incomplete':
        updateData.is_completed = false;
        updateData.completed_at = null;
        break;
      case 'important':
        updateData.is_important = true;
        break;
      case 'unimportant':
        updateData.is_important = false;
        break;
      case 'delete':
        await Task.destroy({
          where: { id: { [Op.in]: task_ids } }
        });
        return res.json(success(null, `成功删除 ${task_ids.length} 个任务`));
    }
    
    const [affectedCount] = await Task.update(updateData, {
      where: { id: { [Op.in]: task_ids } }
    });
    
    res.json(success(null, `成功更新 ${affectedCount} 个任务`));
  })
);

export default router;
